using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Web.UI.WebControls;

namespace Deepcode.Flux.Core.Services.Assistant
{
	/// <summary>
	/// Provides assistance for working with controls
	/// </summary>
	public class ControlUtil
	{
		/// <summary>
		/// Returns a list of ID's corresponding to the values of the selected
		/// items in the list item collection passed in.
		/// </summary>
		/// <param name="cbl"></param>
		/// <returns></returns>
		public static int[] GetListSelectedInts(ListItemCollection list)
		{
			ArrayList al = new ArrayList();
			foreach (ListItem item in list)
			{
				if (item.Selected)
				{
					try
					{
						int val = Int32.Parse(item.Value);
						if (!al.Contains(val)) al.Add(val);
					}
					catch { }
				}
			}
			return al.ToArray(typeof(int)) as int[];
		}
		/// <summary>
		/// Returns a list of selected string values from a list item collection
		/// </summary>
		/// <param name="list"></param>
		/// <returns></returns>
		public static string[] GetListSelectedStrings(ListItemCollection list)
		{
			ArrayList al = new ArrayList();
			foreach (ListItem item in list)
			{
				if (item.Selected)
					if (!al.Contains(item.Value)) al.Add(item.Value);
			}
			return al.ToArray(typeof(string)) as string[];
		}
		/// <summary>
		/// Returns a list of selected string values in CSV format
		/// </summary>
		/// <param name="list"></param>
		/// <returns></returns>
		public static string GetListSelectedCSV(ListItemCollection list)
		{
			string res = "";
			foreach (string s in GetListSelectedStrings(list))
			{
				if (res != "") res += ",";
				res += s;
			}

			return res;
		}
		/// <summary>
		/// Sets each listitem with value in CSVValues to selected
		/// </summary>
		/// <param name="list"></param>
		/// <param name="CSVValues"></param>
		public static void SetSelectedCSV(ListItemCollection list, string CSVValues)
		{
			string [] v = CSVValues.Split(',');
			if( v == null ) return;
			if( v.Length < 1 ) return;

			ArrayList csv = new ArrayList( v );
			foreach (ListItem i in list)
				if( csv.Contains( i.Value )) i.Selected = true;
		}
	}
}
